package cn.laixueit.intercepter;

import cn.laixueit.commons.CookieUtils;
import cn.laixueit.commons.JwtUtils;
import cn.laixueit.commons.UserInfo;
import cn.laixueit.properties.JwtProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyIntercepter implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    public static  ThreadLocal<UserInfo> getThreadLocal(){
        return THREAD_LOCAL;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        // 校验token
        if(StringUtils.isBlank(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        // 登录放行
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            //存入多线程域
            THREAD_LOCAL.set(userInfo);
        } catch (Exception e) {
            // 没有登录
            return false;
        }
        return true;
    }
}
